import {MenuItem, MenuList} from "@/api/menu/type.ts";

// 构建菜单树
export function buildMenuTree(data: MenuList[]): MenuItem[] {
    const menuMap: { [key: number]: MenuItem } = {};
    const menuTree: MenuItem[] = [];

    // 初始化所有菜单项，并添加到 menuMap
    data.forEach(item => {
        menuMap[item.ID] = {...item};
    });

    // 构建层级关系
    data.forEach(item => {
        if (item.parent_id === 0) {
            menuTree.push(menuMap[item.ID]);
        } else {
            if (menuMap[item.parent_id]) {
                if (!menuMap[item.parent_id].children) {
                    menuMap[item.parent_id].children = [];
                }
                menuMap[item.parent_id]?.children?.push(menuMap[item.ID]);
            }
        }
    });

    // 移除没有 children 的字段
    function removeEmptyChildren(menuItems: MenuItem[]) {
        menuItems.forEach(item => {
            if (item.children && item.children.length === 0) {
                delete item.children;
            } else if (item.children) {
                removeEmptyChildren(item.children);
            }
        });
    }

    removeEmptyChildren(menuTree);
    return menuTree;
}

export function filtrationMenuChildrenID(data: MenuList[]) {
    // Create a map to store parent-child relationships
    const parentMap: { [key: number]: MenuList[] } = {};

    // Populate the map with children
    data.forEach(item => {
        if (item.parent_id !== 0) {
            if (!parentMap[item.parent_id]) {
                parentMap[item.parent_id] = [];
            }
            parentMap[item.parent_id].push(item);
        }
    });

    // Recursive function to get IDs with children
    function getIdsWithChildrenRecursively(menu: MenuList, result: Set<number>, parentMap: {
        [key: number]: MenuList[]
    }): void {
        const children = parentMap[menu.ID];

        if (children && children.length > 0) {
            children.forEach(child => {
                result.add(child.ID);
                getIdsWithChildrenRecursively(child, result, parentMap);
            });
        } else {
            result.add(menu.ID);
        }
    }

    const result: Set<number> = new Set();

    // Start with top-level menus (parent_id == 0)
    data.forEach(item => {
        if (item.parent_id === 0) {
            getIdsWithChildrenRecursively(item, result, parentMap);
        }
    });

    // Remove any parent IDs that are in the result set
    data.forEach(item => {
        if (parentMap[item.ID] && parentMap[item.ID].length > 0) {
            result.delete(item.ID);
        }
    });

    return Array.from(result);
}

